#include <iostream>
#include <iomanip>

#include <fcntl.h>

#include "IOError.h"
#include "Counter_DL636G1.h"
#include "DigitalIO_DL636F.h"
#include "ADC_DL642A.h"

using namespace std;


int main(int argc, char *argv[])
{
  const char *device="/tmp/sis1100_00remote";
  int crate;

  cout << "dackel 0.0.0" << endl << endl;

  // open sis1100/3100 pci-to-vme link
  if( !(crate=open(device, O_RDWR, 0)) )
  {
    cout << "ERROR: could not open \"" << device << "\"" << endl;
    exit(1);
  }
  
  vmesysreset(crate);

  // instantiate counter object
  Counter_DL636G1 counter1(crate,0x4420);

  // instantiate io object
  DigitalIO_DL636F io1(crate,0x4400);

  try {
    counter1.reset();

    // output counter values
    cout << "counter1.a == " << counter1.getA() << endl;
    cout << "counter1.b == " << counter1.getB() << endl;
    cout << "counter1.c == " << counter1.getC() << endl << endl;
    
    // enable gate of counter 1;
    cout << "counter1.gate==" << counter1.getGateIn()
	 << " io1.input== " << io1.getInput() << endl;
    io1.setO4(1); if(io1.getO4()!=1) cout << "something's wrong" << endl;

    cout << "counter1.gate==" << counter1.getGateIn()
	 << " io1.input== " << io1.getInput() << endl << endl;

    for( int i=0; i<1000; i++ )
    {
      //increment counter1. a and counter1.b;
      io1.setO1(1);
      if(i%2==0) io1.setO2(1);
      if(i%3==0) io1.setO3(3);
      usleep(1);

      io1.setO1(0);
      if(i%2==0) io1.setO2(0);
      if(i%3==0) io1.setO3(0);
      //      usleep(1);

    }

    cout << dec;

    // output counter values
    cout << "counter1.a == " << counter1.getA() << endl;
    cout << "counter1.b == " << counter1.getB() << endl;
    cout << "counter1.c == " << counter1.getC() << endl;    
  }
  catch( IOError ioe ) {
    cout << "catched IOError expection: " << ioe.getMsg() << endl 
	 << "param=" << ioe.getParam() << endl;
  }
    

  close(crate);

  return 0;
}
